package com.sarnath.sardoop.modules.hive.service;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.sarnath.sardoop.common.spring.PropertyUtil;
import com.sarnath.sardoop.common.utils.JsonMapper;

/**
 * @author yingc
 *hive sql语句执行
 */
@Service("hiveSqlService")
@Lazy(false)
public class HiveSqlService {
	@Resource
	private JdbcTemplate hiveTemplate;
	
	/**
	 * 单行单列数据查询
	 * @param sql
	 * @return
	 */
	public Object queryForObject(String sql){
		return hiveTemplate.queryForObject(sql,new Object[]{}, Object.class);
	}
	/**
	 * 单行数据查询
	 * @param sql
	 * @return
	 */
	public Map<String, Object> queryForMap(String sql){
		return hiveTemplate.queryForMap(sql,new Object[]{});
	}
	/**
	 * 多行数据查询
	 * @param sql
	 * @return
	 */
	public List<Map<String, Object>> queryForList(String sql){
		return hiveTemplate.queryForList(sql, new Object[]{});
	}
	/**
	 * 执行SQL语句
	 * @param sql
	 * @return
	 */
	public void execute(String sql){
		hiveTemplate.execute(sql);
	}
	
	/**
	 * 调用webHcat执行SQL语句
	 * @param sql
	 * @return
	 */
	public Map job(String sql,String outPath){
		RestTemplate restTemplate = new RestTemplate();
		StringBuffer url = new StringBuffer();
		url.append(PropertyUtil.getProperty("webcatUrl"));
		url.append("?user.name=" + PropertyUtil.getProperty("username"));
		HttpHeaders headers = new HttpHeaders();
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String,String>();  
		params.add("execute", sql);
		params.add("statusdir", outPath);
		HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params,headers);
		ResponseEntity<String> exchange = restTemplate.postForEntity(url.toString(), requestEntity, String.class);
		return (Map)JsonMapper.fromJsonString(exchange.getBody(),HashMap.class);
	}
	
}
